import React, { useState, useEffect } from 'react';
import { Space, Table, Tag, Button, Popconfirm, message, Input, Spin } from 'antd';
import { getUserList, resetUserPassword, updateUserStatus } from '@/api/manage';

const { Search } = Input;

function UserMan() {
    const [expanded, setExpanded] = React.useState(false);

    const [loading, setLoading] = useState(false);
    const [isRefresh, setIsRefresh] = useState(false);
    const [data, setData] = useState([]);

    const columns = [
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'username',
            render: (text) => <span>{text}</span>,
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            key: 'email',
            width: 200,
            render: (email) => {
                const truncated = email.slice(0, 3) + '***' + email.slice(email.indexOf('@'));

                return (
                    <span onClick={() => setExpanded(!expanded)} style={{ cursor: 'pointer', color: '#1890ff' }}>
                        {expanded ? email : truncated}
                    </span>
                );
            },
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status) => {
                let color = 'green';
                let text = '正常';
                if (status === 0) {
                    color = 'red';
                    text = '禁用';
                }
                return (
                    <Tag color={color} key={status}>
                        {text}
                    </Tag>
                );
            },
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Popconfirm
                        title="重置密码"
                        description="确定要重置该用户的密码吗?"
                        okText="确定"
                        cancelText="取消"
                        onConfirm={() => {
                            resetUserPassword(record?.userId).then((res) => {
                                if (res.code === 200) {
                                    setIsRefresh(!isRefresh);
                                    message.success('重置密码成功');
                                } else {
                                    message.error('重置密码失败');
                                }
                            });
                        }}
                    >
                        <Button type="link">重置密码</Button>
                    </Popconfirm>
                    {record.status === 1 ? (
                        <Popconfirm
                            title="用户封禁"
                            description="确定要封禁该用户吗?"
                            okText="确定"
                            cancelText="取消"
                            onConfirm={() => {
                                updateUserStatus(record?.userId, 0).then((res) => {
                                    if (res.code === 200) {
                                        setIsRefresh(!isRefresh);
                                        message.success('封禁成功');
                                    } else {
                                        message.error('封禁失败');
                                    }
                                });
                            }}
                        >
                            <Button type="link" danger>
                                封禁用户
                            </Button>
                        </Popconfirm>
                    ) : (
                        <Popconfirm
                            title="用户解封"
                            description="确定要解封该用户吗?"
                            okText="确定"
                            cancelText="取消"
                            onConfirm={() => {
                                updateUserStatus(record?.userId, 1).then((res) => {
                                    if (res.code === 200) {
                                        setIsRefresh(!isRefresh);
                                        message.success('解封成功');
                                    } else {
                                        message.error('解封失败');
                                    }
                                });
                            }}
                        >
                            <Button type="link" style={{ color: '#52c41a' }}>
                                解除封禁
                            </Button>
                        </Popconfirm>
                    )}
                </Space>
            ),
        },
    ];

    // 处理查询逻辑
    const onSearch = (value) => {
        if (value === '') {
            return message.error('查询内容不能为空');
        }
        setLoading(true);
        getUserList(value)
            .then((res) => {
                if (res.code === 200) {
                    setData(res.data);
                    message.success('查询成功');
                }
            })
            .finally(() => setLoading(false));
    };

    useEffect(() => {
        setLoading(true);
        getUserList()
            .then((res) => {
                if (res.code === 200) {
                    setData(res.data);
                }
            })
            .finally(() => {
                setLoading(false);
                setIsRefresh(false);
            });
    }, [isRefresh]);

    return (
        <div
            style={{
                display: 'flex',
                flexDirection: 'column',
                gap: 16,
            }}
        >
            <div
                style={{
                    display: 'flex',
                    flexDirection: 'row',
                    alignItems: 'center',
                    gap: 10,
                }}
            >
                <div
                    style={{
                        fontWeight: 'bold',
                        fontSize: 16,
                    }}
                >
                    查找用户:
                </div>
                <Search
                    placeholder="输入用户名、邮箱搜索"
                    onSearch={onSearch}
                    enterButton
                    style={{
                        width: 300,
                    }}
                />
            </div>
            <Table columns={columns} dataSource={data} loading={loading} rowKey="userId" />
        </div>
    );
}

export default UserMan;
